import plugin from '../../lib/plugins/plugin.js'
import axios from 'axios'
import common from '../../lib/common/common.js'



let headers = {
      "Origin": 'https://huodong3.i3839.com',
      "Referer": 'https://huodong3.3839.com/n/hykb/cornfarm/index.php?imm=0',
      'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
      'User-Agent': 'Mozilla/5.0 (Linux; Android 13; M2012K11AC Build/TKQ1.220829.002; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/115.0.5790.166 Mobile Safari/537.36Androidkb/1.5.7.005(android;M2012K11AC;13;1080x2320;WiFi);@4399_sykb_android_activity@'
 }

export class HYKB extends plugin {
    constructor () {
      super({
        name: 'hykb',
        dsc: "好游快爆签到",
        event: 'message',
        priority: 6000,
        rule: [
          {
            reg: "^#(hykb|kb|好游快爆)签到$",
            fnc: "hykbqd"
          },
          {
            reg:"^#(hykb|kb|好游快爆|快爆)设置ck$",
            fnc: "kbsookie"
          },
          {
            reg: "^#(hykb|kb|好游快爆)全部签到$",
            fnc:"allsign"
          }
        ]
      })
    }
    
    async hykbqd(e) {
        let consequence = await hykblogin(e.user_id)
        logger.info(consequence)
        if(consequence.code == 200 && consequence.msg.key == 1001) {
            return e.reply(`好游快爆今日已浇水\n今日获得爆米花：${consequence.msg.sign.sign_now_bmh}\n今日获得经验：${consequence.msg.sign.sign_now_csd}`)
        } else if(consequence.code == 200 && consequence.msg.key == "ok") {
            let msg = `签到成功，信息如下\n获得${consequence.msg.add_baomihua}个爆米花\n目前一共有${consequence.msg.baomihua}个爆米花\n浇灌进度${consequence.msg.csd_jdt}`
            return e.reply(msg)
        } else if(consequence.code == 404){
            return e.reply(consequence.msg)
        } else {
            logger.info(consequence)
            return e.reply(`好游快爆浇水出现异常`)
        }
    }
    
    async kbsookie(e) {
        this.setContext('doRep')
        let text = ""
        if(e.group_id) {
            text = "请发送好游快爆的sookie\n\n注意！你现在处在群聊当中，请发送scookei后及时撤回信息！本bot不会恶意储存你的scookie"
        } else {
            text = "请发送好游快爆的sookie"
        }
        
        await this.reply(text)
        return true
    }
    
    async doRep() {
        let scookie = this.e.msg
        let cookie = await redis.get(`HYKB:SIGN:${this.e.user_id}`)
        let env = await redis.get(`HYKB:SIGN`)
        //判断有没有全局数据库，这个用来全部签到数据储存
        if(!env) {
            let data = []
            data.push({ "userId": this.e.user_id, "scookie": scookie })
            await redis.set(`HYKB:SIGN`, JSON.stringify(data))
        }
        
        //判断全局数组里面有没有该用户的数据
        let env1 = await redis.get(`HYKB:SIGN`)
        let parsedArray = JSON.parse(env1)
        if(!parsedArray.some(item => item.userId === this.e.user_id)) {
            parsedArray.push({ "userId": this.e.user_id, "scookie": scookie })
            await redis.set(`HYKB:SIGN`, JSON.stringify(parsedArray))
        } else {
            //更新指定用户的scookie
            const targetIndex = parsedArray.findIndex(item => item.userId === this.e.user_id);
            parsedArray[targetIndex].scookie = scookie
            await redis.set(`HYKB:SIGN`, JSON.stringify(parsedArray))
        }
        
        //不判断，用户每次设置都会更新scookie      
        await redis.set(`HYKB:SIGN:${this.e.user_id}`, scookie)
        
        let consequence = await hykblogintest(this.e.user_id)
        this.finish('doRep')
        return this.e.reply(consequence)
    }
    
    //全部签到
    async allsign(e) {
        //获取全局数据库内容
        let key = await redis.get("HYKB:SIGN")
        let parsedArray = JSON.parse(key)
        //let lengt = parsedArray.length
        if(!key) {
           return e.reply("全局数据库内暂时没有需要签到的好游快爆用户") 
        }
        
        let text = ""
        
        //成功
        let success = 0
        //已签到
        let Checked = 0
        //失败
        let fail = 0
        //异常
        let Abnormal = 0
        
        await e.reply(`本次需要签到${lengt}个用户，预计需要时间${lengt * 15}秒`)
        await hykbALLsign(lengt, 15, async (i) => {
            //调用签到界面的登录接口
            let UserID = parsedArray[i].userId
            let request = await hykblogin(UserID)
            //输出日志，用于开发
            //logger.info(request)
            if(request.code == 501) {
                fail++
                text += `用户${UserID}签到失败\n原因：好游快爆登录失败\n---------------\n`
            } else if(request.code == 200 && request.msg.key == "ok") {
                success++
                text += `用户${UserID}签到成功\n结果：获得${request.msg.add_baomihua}爆米花\n---------------\n`
            } else if(request.code == 200 && request.msg.key == "1001") {
                Checked++
                text += `用户${UserID}已签到\n结果：已获得${request.msg.sign.sign_now_bmh}爆米花\n---------------\n`
            } else if(request.code == 200 && request.msg.key == "Device0therBand"){
                fail++
                text += `用户${UserID}签到失败\n原因：设备号第二次绑定，请到好游快爆解决\n---------------\n`
            } else {
                Abnormal++
                text += `用户${UserID}签到异常---------------\n`
            }
        })
        text += `本次共签到${lengt}个用户\n${success}个签到成功\n${Checked}个已签到\n${fail}个签到失败\n${Abnormal}个签到异常`
        const msg = await common.makeForwardMsg(e, text, '好游快爆签到日志')
        await this.reply(msg)
    }
}


//签到
async function hykbSign(userId) {
    let url = "https://huodong3.3839.com/n/hykb/cornfarm/ajax_sign.php"
    let r = Math.random().toFixed(16);
    let cookie = await redis.get(`HYKB:SIGN:${userId}`)
    if(!cookie) {
        return { "code": 404, "msg": "未找到你的ck\n请使用 #hykb设置ck+ck 来设置scookie"}
    }
    
    let data = `ac=Sign&verison=1.5.7.005&OpenAutoSign=&r=${r}&scookie=${cookie}`
    let request = await axios.post(url, data, { headers: headers })
    return request
}

//登录
async function hykblogin(userId) {
    let url = "https://huodong3.3839.com/n/hykb/cornfarm/ajax.php"
    let r = Math.random().toFixed(16);
    let cookie = await redis.get(`HYKB:SIGN:${userId}`)
    if(!cookie) {
        return { "code": 404, "msg": "未找到你的ck\n请使用 #hykb设置ck+ck 来设置scookie"}
    }
    
    let data = {
        "ac": "login",
        "r": r,
        "scookie": cookie
    }
    
    let request = await axios.post(url, data, { headers: headers })
    if(request.data.key == "ok") {
        //登录成功后调用签到功能
        let consequence = await hykbSign(userId)
        return { "code": 200, "msg": consequence.data}
    } else {
        return { "code": 501, "msg":  `hykb登录失败\n${JSON.stringify(request.data)}`}
    }
}

//sookie验证
async function hykblogintest(userId) {
    let url = "https://huodong3.3839.com/n/hykb/cornfarm/ajax.php"
    let r = Math.random().toFixed(16);
    let cookie = await redis.get(`HYKB:SIGN:${userId}`)
    if(!cookie) {
        return { "code": 404, "msg": "未找到你的ck\n请使用 #hykb设置ck+ck 来设置scookie"}
    }
    
    let data = {
        "ac": "login",
        "r": r,
        "scookie": cookie
    }
    
    let request = await axios.post(url, data, { headers: headers })
    if(request.data.key == "ok") {
        return `scookie验证成功，欢迎好游快爆用户 『 ${request.data.config.name} 』`
    } else {
        return `scookie验证失败\n${JSON.stringify(request.data)}`
    }
}


//实现循环延迟
async function hykbALLsign(iterations, delayInSeconds, callback) {
    return new Promise((resolve) => {
        let counter = 0;
        const intervalId = setInterval(async () => {
            if (counter < iterations) {
                await callback(counter);
                counter++
            } else {
                clearInterval(intervalId);
                resolve();
            }
        }, delayInSeconds * 1000)
    })
}